package com.brush.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.CacheConstants;
import com.brush.common.exception.ServiceException;
import com.brush.common.exception.database.PrimaryKeyException;
import com.brush.common.exception.database.RecordNotFoundException;
import com.brush.common.utils.MessageUtils;
import com.brush.system.domain.SysNotice;
import com.brush.system.domain.req.sysnotice.SysNoticeAddReq;
import com.brush.system.domain.req.sysnotice.SysNoticeEditReq;
import com.brush.system.domain.req.sysnotice.SysNoticeQueryReq;
import com.brush.system.domain.resp.sysnotice.SysNoticeQueryResp;
import com.brush.system.mapper.SysNoticeMapper;
import com.brush.system.service.SysNoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author 18494
 * @description 针对表【sys_notice(通知公告表)】的数据库操作Service实现
 * @createDate 2024-08-19 10:28:03
 */
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice>
        implements SysNoticeService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageInfo<SysNoticeQueryResp> paginationQuery(SysNoticeQueryReq req) {
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            // 调用sysConfigMapper[mybatis]的分页查询方法, 要么使用lambdaQueryWrapper来写【mybatis-plus】
            // 一定返回的结果是 List<SysConfigResp>
            this.baseMapper.paginationQuery(req);
        });
    }

    @Override
    public boolean add(SysNoticeAddReq req) {
        // 验证noticeTitle是否已经存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<SysNotice>().eq(SysNotice::getNoticeTitle, req.getNoticeTitle()))) {
            throw new ServiceException(MessageUtils.message("sysnotice.noticeTitle.exists"));
        }
        SysNotice newEntity = new SysNotice();
        BeanUtils.copyProperties(req, newEntity);
        boolean save = this.save(newEntity);

        if (save) {
            // 清空缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_NOTICE_ID + req.getNoticeTitle(), newEntity);
        }
        return save;
    }

    @Override
    public SysNoticeQueryResp findById(Long id) {
        if (Objects.isNull(id)) {
            throw new PrimaryKeyException();
        }

        // 根据主键查询
        SysNoticeQueryResp db = this.baseMapper.findById(id);

        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        return db;
    }

    @Override
    public boolean edit(SysNoticeEditReq req) {
        // 根据主键查询
        SysNotice db = this.getById(req.getNoticeId());
        // 数据库找不到数据
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        // 验证noticeTitle是否已经存在
        if (!req.getNoticeTitle().equals(db.getNoticeTitle())) {
            // 判断noticeTitle是否已经被使用
            if (this.baseMapper.exists(new LambdaQueryWrapper<SysNotice>().eq(SysNotice::getNoticeTitle, req.getNoticeTitle()))) {
                throw new ServiceException(MessageUtils.message("sysconfig.noticeTitle.exists"));
            }
        }

        // 覆盖数据库对象的值
        BeanUtils.copyProperties(req, db);
        boolean result = this.updateById(db);
        if (result) {
            // 覆盖缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + db.getNoticeTitle(), db);
        }
        return result;
    }

    /**
     * 删除sysconfig指定的id并删除缓存
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Long[] ids) {
        if (Objects.isNull(ids) || ids.length == 0) {
            throw new PrimaryKeyException();
        }

        final SysNoticeServiceImpl sysNoticeService = this;

        this.redisTemplate.execute(new SessionCallback<Void>() {
            @Override
            public Void execute(RedisOperations operations) throws DataAccessException {
                // 开启redis事务
                operations.multi();

                // 循环删除数据库数据，时间复杂度：O(n)，事务问题
                try {
                    for (Long id : ids) {
                        SysNotice db = sysNoticeService.getById(id);
                        // 数据库找到数据
                        if (Objects.nonNull(db)) {
                            // 删除数据库中的值
                            sysNoticeService.removeById(id);
                            // 删除缓存中的值
                            String redisKey = CacheConstants.SYS_CONFIG_KEY + db.getNoticeTitle();
                            operations.delete(redisKey);
                        }
                    }
                    // 提交redis事务
                    operations.exec();
                } catch (Exception e) {
                    // 回滚redis事务
                    operations.discard();
                    throw e;
                }
                return null;
            }
        });
        return true;
    }


}




